<template>
	<view class="statement-management">
		<!-- 搜索和筛选区域 -->
		<view class="search-bar">
			<uni-search-bar v-model="searchKeyword" placeholder="单号或流水号" @confirm="handleSearch" @clear="handleSearchClear"
				cancelButton="none" style="flex: 1;" />
			<view class="date-picker">
				<uni-datetime-picker type="datetimerange" returnType="timestamp" v-model="dateRange"
					@change="handleDateChange" />
			</view>
		</view>

		<!-- 结算单列表 -->
		<view class="list-container">
			<view v-for="(statement,index) in filteredStatements" :key="index" class="statement-card">
				<view class="card-header">
					<text class="order-number">单号: {{ statement.number }}</text>
					<button class="detail-btn" @click="showDetail(statement)">详情&修改</button>
				</view>
				<view class="card-body">
					<view class="info-row">
						<view class="info-row-left">
							<text class="info-label">流水号:</text>
							<text class="info-value">{{ statement.turnoverNumber || '无' }}</text>
						</view>
						<view class="info-row-right">
							<text class="pay-method" :class="getPayMethodClass(statement.payMethod)">
								{{ getPayMethodText(statement.payMethod) }}
							</text>
						</view>
					</view>
					<view class="info-row">
						<view class="info-row-left">
							<text class="info-label">结账时间:</text>
							<text class="info-value">{{ statement.createTimeTemp }}</text>
						</view>
						<view class="info-row-right">
							<text class="info-label">应收金额: </text>
							<text class="info-value amount"> ¥{{ statement.amount?.toFixed(2) }}</text>
						</view>
					</view>
					<view class="info-row">
						<view class="info-row-left">
							<text class="info-label">操作人:</text>
							<text class="info-value">{{ statement.createUserName || '未知' }}</text>
						</view>
						<view class="info-row-right">
							<text class="info-label">实收金额:</text>
							<text class="info-value pay-amount">¥{{ statement.payAmount?.toFixed(2) }}</text>
						</view>
					</view>
					<view class="info-row-remark" v-if="statement.remarkTemp">
						<text class="info-remark-label">备注:</text>
						<text class="info-remark-content">{{ statement.remarkTemp }}</text>
					</view>
				</view>
			</view>

			<uni-load-more :status="loadStatus" @clickLoadMore="showMoreData"></uni-load-more>
			<view class="safe-area-box"></view>
		</view>

		<!-- 结算单详情弹窗 -->
		<uni-popup ref="detailPopup" type="center" style="z-index: 20;">
			<view class="detail-popup">
				<!-- 弹窗头部 -->
				<view class="popup-header">
					<text class="popup-title">结算单详情</text>
					<uni-icons type="closeempty" size="24" color="#ff5a5f" @click="closeDetail"></uni-icons>
				</view>

				<!-- 弹窗内容 -->
				<view class="popup-content">
					<!-- 基本信息卡片 -->
					<view class="info-card">
						<view class="card-title">基本信息</view>
						<view class="info-grid">
							<view class="info-item">
								<text class="info-label">单号</text>
								<text class="info-value">{{ currentStatement.number }}</text>
							</view>
							<view class="info-item">
								<text class="info-label">流水号</text>
								<text class="info-value">{{ currentStatement.turnoverNumber || '无' }}</text>
							</view>
							<view class="info-item">
								<text class="info-label">支付方式</text>
								<text class="info-value">{{ getPayMethodText(currentStatement.payMethod) }}</text>
							</view>
							<view class="info-item">
								<text class="info-label">应收金额</text>
								<text class="info-value amount">¥{{ calculateTotal.toFixed(2) }}</text>
							</view>
							<view class="info-item">
								<text class="info-label">结账时间</text>
								<text class="info-value">{{ currentStatement.createTimeTemp }}</text>
							</view>
							<view class="info-item">
								<text class="info-label">实收金额</text>
								<text v-if="!isEditPayAmount" class="info-value pay-amount"
									@click="isEditPayAmount=true">¥{{ payAmount?.toFixed(2) }}</text>
								<input class="info-value pay-amount-input" v-else v-model.number="payAmount" focus
									@blur="isEditPayAmount=false" />
							</view>
						</view>
					</view>

					<!-- 菜品明细卡片 -->
					<view class="dish-card" v-if="detailList.length > 0">
						<view class="card-title">菜品明细</view>
						<view class="dish-header">
							<text class="dish-col name">菜品名称</text>
							<text class="dish-col">数量</text>
							<text class="dish-col">单价</text>
							<text class="dish-col">小计</text>
						</view>
						<view class="dish-list">
							<view class="dish-item" v-for="(dish,index) in detailList" :key="index">
								<text class="dish-col name">{{dish._id? '':'**'}}{{dish.name}}</text>
								<text class="dish-col">{{ dish.number }}</text>
								<text class="dish-col">¥{{ dish.amount.toFixed(2) }}</text>
								<text class="dish-col">¥{{ (dish.amount * dish.number).toFixed(2) }}</text>
							</view>
							<view class="dish-item" v-if="isAdjust">
								<input class="dish-col name" v-model="adjustData.name" @confirm="handleAdjust"
									:class="{'adjust':isAdjust}" />
								<input class="dish-col" v-model.number="adjustData.number" @confirm="handleAdjust"
									:class="{'adjust':isAdjust}" />
								<input class="dish-col" v-model.number="adjustData.amount" focus @confirm="handleAdjust"
									:class="{'adjust':isAdjust}" />
								<text class="dish-col"></text>
							</view>
						</view>
						<view class="dish-total">
							<button size="mini" class="btn" :class="{'adjust':isAdjust}"
								@click="handleAdjust">{{isAdjust?'保存调整':'调整'}}</button>
							<text class="total-amount">总计: ¥{{ calculateTotal.toFixed(2) }}</text>
						</view>
					</view>

					<!-- 备注信息 -->
					<view class="remark-card">
						<view class="card-title">备注信息</view>
						<textarea class="remark-content" v-model="editRemark" auto-height />
					</view>
				</view>

				<!-- 弹窗底部 -->
				<view class="popup-footer">
					<button class="popup-close-btn" @click="closeDetail">关闭</button>
					<button :disabled="!isEdit||isAdjust" class="popup-save-btn" :class="{'disabled-btn':!isEdit||isAdjust}"
						@click="saveEdit">保存修改</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue';
	import {
		getStatementDetail,
		getStatements,
		updateStatement
	} from '../api/statement';
	import {
		formatDate,
		mergeStatementDetail
	} from '../utiles/user';
	import {
		onShow
	} from '@dcloudio/uni-app'

	// 结算单数据
	const statements = ref([]);
	const searchKeyword = ref('');
	const dateRange = ref([]);
	let page = 1;
	let pageSize = 5;
	const loadStatus = ref('more');

	// 支付方式选项
	const payMethodOptions = ref([{
			value: '',
			text: '全部支付方式'
		},
		{
			value: 1,
			text: '微信'
		},
		{
			value: 2,
			text: '支付宝'
		},
		{
			value: 3,
			text: '现金'
		},
		{
			value: 4,
			text: 'POS机'
		},
		{
			value: 5,
			text: '闪付'
		},
		{
			value: 6,
			text: '其他'
		}
	]);

	// 详情弹窗相关
	const detailPopup = ref(null);
	const currentStatement = ref({});

	// 初始化加载数据
	onMounted(() => {
		getListData(1);
	});

	// 获取结算单数据
	const getListData = async (page1 = 0) => {
		if (page1) {
			loadStatus.value = 'more';
			statements.value = [];
			page = page1;
		}
		if (loadStatus.value === 'loading') {
			return;
		}
		if (loadStatus.value === 'no-more') {
			uni.showToast({
				title: '没有更多数据了...',
				icon: 'none'
			});
			return;
		}

		loadStatus.value = 'loading';

		const params = {
			keyword: searchKeyword.value.trim(),
			startDate: dateRange.value[0] || '',
			endDate: dateRange.value[1] || '',
			page,
			pageSize
		};

		const res = await getStatements(params);

		if (res && res.length > 0) {
			res.forEach(item => {
				item.createTimeTemp = formatDate(item.createTime, true)
				const index = item.remark ? item.remark.indexOf(',调整：') : -1
				if (index != -1) {
					item.remarkTemp = item.remark.slice(0, index)
				} else {
					item.remarkTemp = item.remark
				}
			})
			statements.value.push(...res);
		}
		console.log("列表数据：", statements.value);

		if (!res || res.length < pageSize) {
			loadStatus.value = 'no-more';
		} else {
			loadStatus.value = 'more';
		}
	};

	// 触底加载更多
	const showMoreData = () => {
		if (loadStatus.value === 'more') {
			page++;
			getListData();
		}
	};

	const filteredStatements = computed(() => {
		return statements.value.filter(statement => {
			// 1. 关键词搜索（单号或流水号）
			const keywordMatch = searchKeyword.value.trim() === '' ||
				(statement.number && statement.number.includes(searchKeyword.value.trim())) ||
				(statement.turnoverNumber && statement.turnoverNumber.includes(searchKeyword.value.trim()));

			// 2. 日期范围筛选
			let dateMatch = true;
			if (dateRange.value && dateRange.value.length === 2) {
				const [startDate, endDate] = dateRange.value;
				const statementTime = statement.timestamp || new Date(statement.createTime).getTime();
				dateMatch = statementTime >= startDate && statementTime <= endDate;
			}

			return keywordMatch && dateMatch;
		});
	});

	// 搜索结算单
	const handleSearch = () => {
		getListData(1);
	};

	// 清空搜索
	const handleSearchClear = () => {
		searchKeyword.value = '';
		getListData(1);
	};

	// 日期变化处理
	const handleDateChange = (e) => {
		dateRange.value = e
		getListData(1);
	};

	// 获取支付方式文本
	const getPayMethodText = (method) => {
		switch (method) {
			case 1:
				return '微信';
			case 2:
				return '支付宝';
			case 3:
				return '现金';
			case 4:
				return 'POS机';
			case 5:
				return '闪付';
			case 6:
				return '其他';
		}
	};

	// 获取支付方式样式类
	const getPayMethodClass = (method) => {
		switch (method) {
			case 1:
				return 'wechat';
			case 2:
				return 'alipay';
			case 3:
				return 'cash';
			case 4:
				return 'pos';
			case 5:
				return 'unionpay';
			case 6:
				return 'other';
		}
	};

	const detailList = ref([])
	// 计算菜品总金额
	const calculateTotal = computed(() => {
		return detailList.value.reduce((acc, cur) => acc + cur.number * cur.amount, 0)
	});
	const isEditPayAmount = ref(false)
	const isAdjust = ref(false)
	const editRemark = ref('')
	const payAmount = ref(0)
	const adjustData = ref({
		name: '',
		number: 0,
		amount: 0
	})
	const isEdit = computed(() => {
		return editRemark.value !== currentStatement.value.remarkTemp || calculateTotal.value !== currentStatement.value
			.amount || payAmount.value !== currentStatement.value.payAmount
	})
	// 显示详情
	const showDetail = async (statement) => {
		const res = await getStatementDetail(statement._id)
		console.log(res);
		detailList.value = mergeStatementDetail(res)
		currentStatement.value = statement;
		editRemark.value = statement.remarkTemp
		payAmount.value = statement.payAmount
		const index = statement.remark.indexOf(',调整：')
		if (index != -1) {
			const arr = statement.remark.slice(index + ',调整：'.length).split('*')
			detailList.value.push({
				_id: '',
				name: arr[0],
				number: Number(arr[1]),
				amount: Number(arr[2])
			})
		}
		detailPopup.value.open();
	};

	const handleAdjust = () => {
		if (isAdjust.value) {
			adjustData.value.name = adjustData.value.name.trim()
			if (!adjustData.value.name) {
				uni.showToast({
					title: '名称不能为空',
					icon: 'none'
				})
				return
			}
			isAdjust.value = false
			if (adjustData.value.number !== 0 && adjustData.value.amount !== 0) {
				detailList.value.push({
					_id: '',
					name: adjustData.value.name,
					number: adjustData.value.number,
					amount: adjustData.value.amount
				})
			}
		} else {
			if (detailList.value[detailList.value.length - 1]._id === '') {
				adjustData.value = detailList.value.pop()
			} else {
				adjustData.value = {
					name: '退货',
					number: -1,
					amount: 0
				}
			}
			isAdjust.value = true
		}
	}

	const saveEdit = () => {
		const data = {
			_id: currentStatement.value._id
		}
		if (detailList.value[detailList.value.length - 1]._id === '') {
			data.remark = editRemark.value + ',调整：' + adjustData.value.name + '*' +
				adjustData.value.number + '*' + adjustData.value.amount
		} else {
			data.remark = editRemark.value
		}
		data.amount = calculateTotal.value
		data.payAmount = payAmount.value
		updateStatement(data).then(() => {
			currentStatement.value.remark = data.remark
			currentStatement.value.amount = data.amount
			currentStatement.value.payAmount = data.payAmount
			currentStatement.value.remarkTemp = editRemark.value
		})
	}

	// 关闭详情
	const closeDetail = () => {
		detailPopup.value.close();
	};

	defineExpose({
		showMoreData,
		getListData
	});
</script>

<style lang="scss" scoped>
	.statement-management {
		height: 100%;
		display: flex;
		flex-direction: column;
		background-color: #f5f5f5;
	}

	.search-bar {
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx 20rpx 20rpx;
		background-color: #ffffff;
		border-bottom: 1rpx solid #eee;
		box-sizing: border-box;
		width: 100%;
		height: 150rpx;
		position: fixed;
		top: 80rpx;
		left: 0;
		z-index: 5;

		.date-picker {
			margin: 0 10rpx;
			width: 300rpx;
		}

	}

	.list-container {
		flex: 1;
		padding: 20rpx;
		margin-top: 225rpx;
	}

	.statement-card {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 0rpx 6rpx rgba(0, 0, 0, 0.1);

		.card-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;
			padding-bottom: 10rpx;
			border-bottom: 1rpx solid #eee;

			.order-number {
				font-size: 28rpx;
				font-weight: 700;
				color: #333;
			}

			.detail-btn {
				font-size: 24rpx;
				height: 50rpx;
				line-height: 50rpx;
				padding: 0 20rpx;
				background-color: #ff5a5f;
				color: white;
				font-weight: 700;
				margin: 0 20rpx;
			}
		}

		.card-body {
			line-height: 44rpx;

			.info-row {
				display: flex;
				margin-bottom: 8rpx;
				font-size: 26rpx;

				.info-row-left,
				.info-row-right {
					.info-label {
						width: 140rpx;
						color: #666;
						margin-right: 20rpx;
					}

					.info-value {
						flex: 1;
						color: #333;

						&.amount {
							color: #ff5a5f;
							font-weight: bold;
						}

						&.pay-amount {
							color: #52C41A;
							font-weight: bold;
						}

						&.remark {
							color: #999;
							font-size: 24rpx;
						}
					}
				}

				.info-row-left {
					width: 60%;
				}

				.info-row-right {
					.pay-method {
						font-size: 24rpx;
						padding: 4rpx 12rpx;
						border-radius: 4rpx;

						&.wechat {
							background-color: #07C160;
							color: white;
						}

						&.alipay {
							background-color: #1677FF;
							color: white;
						}

						&.cash {
							background-color: #52C41A;
							color: white;
						}

						&.pos {
							background-color: #722ED1;
							color: white;
						}

						&.unionpay {
							background-color: #F5222D;
							color: white;
						}

						&.other {
							background-color: #666666;
							color: white;
						}
					}
				}
			}

			.info-row-remark {
				display: flex;
				font-size: 26rpx;
				border-top: 1rpx solid #eee;
				padding-top: 4rpx;

				.info-remark-label {
					width: 60rpx;
					color: #888;
					margin-right: 20rpx;
				}

				.info-remark-content {
					flex: 1;
					color: #888;
				}
			}
		}

		.card-footer {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-top: 20rpx;
			padding-top: 10rpx;
			border-top: 1rpx solid #eee;

			.operator {
				font-size: 24rpx;
				color: #999;
			}

		}
	}

	.safe-area-box {
		height: env(safe-area-inset-bottom);
	}

	.detail-popup {
		width: 90vw;
		max-height: 85vh;
		background: #fff;
		border-radius: 16rpx;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);

		.popup-header {
			padding: 28rpx 32rpx;
			background: linear-gradient(135deg, #1685A9, #1DA1F2);
			display: flex;
			justify-content: space-between;
			align-items: center;
			box-shadow: 0 5rpx 8rpx rgba(0, 0, 0, 0.2);
			z-index: 40;

			.popup-title {
				font-size: 34rpx;
				font-weight: 600;
				color: #fff;
			}
		}

		.popup-content {
			flex: 1;
			padding: 24rpx;
			overflow-y: auto;
		}

		.info-card,
		.dish-card,
		.remark-card {
			background: #fff;
			border-radius: 12rpx;
			padding: 24rpx;
			margin-bottom: 24rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

			.card-title {
				font-size: 30rpx;
				font-weight: 600;
				color: #ff5a5f;
				margin-bottom: 24rpx;
				padding-bottom: 16rpx;
				border-bottom: 1rpx solid #f0f0f0;
			}
		}

		.info-grid {
			display: grid;
			grid-template-columns: repeat(2, 1fr);
			gap: 20rpx;

			.info-item {
				display: flex;
				flex-direction: column;

				.info-label {
					font-size: 26rpx;
					color: #888;
					margin-bottom: 8rpx;
				}

				.info-value {
					font-size: 28rpx;
					color: #333;

					&.amount {
						color: #ff5a5f;
						font-weight: bold;
					}

					&.pay-amount {
						color: #52C41A;
						font-weight: bold;
					}

					&.pay-amount-input {
						font-size: 28rpx;
					}
				}
			}
		}

		.dish-header {
			display: flex;
			padding: 16rpx 0;
			border-bottom: 1rpx solid #f0f0f0;
			font-size: 26rpx;
			font-weight: 500;
			color: #666;

			.dish-col {
				flex: 1;
				text-align: center;

				&.name {
					flex: 2;
					text-align: left;
				}
			}
		}

		.dish-list {
			.dish-item {
				display: flex;
				padding: 20rpx 0;
				border-bottom: 1rpx dashed #f0f0f0;
				align-items: center;

				.dish-col {
					flex: 1;
					font-size: 26rpx;
					color: #333;
					text-align: center;

					&.name {
						flex: 2;
						text-align: left;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}
				}
			}
		}

		.dish-total {
			display: flex;
			align-items: baseline;
			margin-top: 30rpx;
			font-size: 28rpx;
			box-sizing: border-box;
			padding-right: 30rpx;

			.btn {
				flex: 1;
				margin: 0 50rpx 0 20rpx;
				color: #333;
				border: 1rpx solid #ddd;
				background-color: #f8f8f8;

				&.adjust {
					background-color: #ff5a5f;
					color: white;
					font-weight: 600;
				}
			}

			.total-amount {
				color: #ff5a5f;
				font-weight: bold;
			}
		}

		.remark-content {
			font-size: 26rpx;
			color: #666;
			line-height: 1.6;
		}

		.popup-footer {
			display: flex;
			padding: 20rpx;
			background: #f9f9f9;
			box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.2);
			z-index: 40;

			.popup-close-btn {
				width: 45%;
				height: 80rpx;
				line-height: 80rpx;
				background-color: #eee;
				color: #999;
				font-size: 30rpx;
			}

			.popup-save-btn {
				width: 45%;
				height: 80rpx;
				line-height: 80rpx;
				background: linear-gradient(135deg, #1685A9, #1DA1F2);
				color: white;
				font-size: 30rpx;
				transition: all 0.3s ease;

				&.disabled-btn {
					background: linear-gradient(135deg, #cccccc, #999999) !important;
					opacity: 0.8;
				}

				&:not(:disabled):active {
					transform: scale(0.98);
				}
			}
		}
	}
</style>